<?php

namespace Lib;

use Common;
use Exception;
use Sdk\lib\Core;
use Sdk\lib\Config;
use Sdk\lib\DiscuzRestful;

class Site {

	public static function __callStatic($name, $arguments) {
		return Core::RequestWit(__CLASS__, $name, $arguments, Core::Type_StaticMethod);
	}

	// SDK/Client 端不需要校验，永远返回成功
	public static function AdminSignCheck() {
		return array('uid' => 1);
	}

	public static function GetSetting() {
		$settingValue = array();
		$file = PLUGIN_PATH . 'conf/setting.php';
		if (file_exists($file)) {
			include $file;
		}
		return $settingValue;
	}

	public static function GetCommand($key = '') {
		$commandValue = array();
		$file = PLUGIN_PATH . 'conf/command.php';
		if (file_exists($file)) {
			include $file;
		}
		if ($key) {
			return $commandValue[$key] ?? null;
		} else {
			return $commandValue;
		}
	}

	public static function Client_Page($params) {
		if (!empty($params['file'])) {
			foreach ($params['file'] as $k => $v) {
				$_ENV['FILES'][$v['tmp_name']] = $v['tmp_name'];
			}
		}
		return Core::RequestWit(__CLASS__, __FUNCTION__, array($params), Core::Type_StaticMethod);
	}

	const RestfulDefaultKey = 'witSdkDzRF_';

	public static function Discuz_Restful($uri, $params = array()) {
		if (!empty($_GET['_authSign'])) {
			$params['_authSign'] = $_GET['_authSign'];
		}
		if (empty($params['_rKey'] = $_COOKIE['_rKey'])) {
			setcookie('_rKey', $params['_rKey'] = Common::random(7, 1), array('secure' => true, 'samesite' => 'None'));
		}

		$conf = Config::GetRoot('discuz');
		$r = DiscuzRestful::getInstance($conf['website'], $conf['appid'], $conf['secret']);
		$r->restfulKey = $params['_rKey'];

		$cache = Common::memory('get', self::RestfulDefaultKey . $r->restfulKey);
		if (!$cache || !isset($cache['v'])) {
			$r->token = self::_restfulToken($r);
		} else {
			$r->token = $cache['v']['token'];
		}

		$ret = $r->request($uri, $params);
		if (!empty($ret) && $ret['ret'] == -106) {
			$r->token = self::_restfulToken($r, $r->token);
			$ret = $r->request($uri, $params);
		}
		return $ret;
	}

	private static function _restfulToken(&$r, $oldToken = '') {
		$ret = $r->request('/token', !$oldToken ? array() : array('token' => $oldToken));
		if (!$ret || $ret['ret'] > 0 || empty($ret['token'])) {
			throw new Exception('restful token is error');
		}
		Common::memory('set', self::RestfulDefaultKey . $r->restfulKey, array('v' => $ret), $ret['expires_in']);
		return $ret['token'];
	}

}